package cn.sdhuijin.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @author sunp@sdhuijin.cn
 * @version 创建时间：2015年1月28日 下午4:38:42 读写Properties文件
 */
public class PropertiesUtil {

	/**
	 * 根据Key读取Value
	 * 
	 * @param filePath
	 * @param key
	 * @return
	 */
	public static String GetValueByKey(String filename, String key) {
		Properties pps = new Properties();

		try {
			String filePath = PropertiesUtil.class.getClassLoader()
					.getResource(filename).getPath();
			InputStream in = new BufferedInputStream(new FileInputStream(
					filePath));
			pps.load(in);
			String value = pps.getProperty(key);
			return value;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 写入Properties信息
	 * 
	 * @param filePath
	 * @param pKey
	 * @param pValue
	 * @throws IOException
	 */
	public static void WriteProperties(String filename, String pKey,
			String pValue) throws IOException {
		Properties pps = new Properties();
		String filePath = PropertiesUtil.class.getClassLoader()
				.getResource(filename).getPath();
		InputStream in = new FileInputStream(filePath);
		pps.load(in);
		OutputStream out = new FileOutputStream(filePath);
		pps.setProperty(pKey, pValue);
		pps.store(out, "Update " + pKey + " value");
		if (in != null) {
			in.close();
		}
		if (out != null) {
			out.close();
		}
	}

	public String getClassDirectory() {
		String cla = this.getClass().getClassLoader().getResource(".")
				.getPath();
		return cla;
	}

	public static void main(String[] args) throws IOException {
		// WriteProperties("ftp.properties", "long", "212");
		String value = GetValueByKey("ftp.properties", "port");
		System.out.println(value);
	}

}
